<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-button type="primary">添加角色</el-button>
      <!-- 表格区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 第一大部分 -->
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="index == 0 ? 'btop' : ''"
              class="row-padding bbottom vcenter"
            >
              <!-- 左侧 -->
              <el-col :span="5">
                <el-tag closable class="mr" @close="removeRight(scope.row, item.id)">
                  {{ item.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 右侧 -->
              <el-col :span="19">
                <!-- 第二大部分 -->
                <el-row
                  v-for="(subItem, subIndex) in item.children"
                  :key="subItem.id"
                  class="row-padding vcenter"
                  :class="subIndex < item.children.length - 1 ? 'bbottom' : ''"
                >
                  <!-- 左侧 -->
                  <el-col :span="6">
                    <el-tag type="success" closable class="mr" @close="removeRight(scope.row, subItem.id)">
                      {{ subItem.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 右侧 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      v-for="subsubItem in subItem.children"
                      :key="subsubItem.id"
                      class="secondPart-right"
                      @close="removeRight(scope.row, subsubItem.id)"
                    >
                      {{ subsubItem.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"
              >编辑</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="mini"
              >删除</el-button
            >
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showDialogVisible(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="rightsDialogVisible"
      width="50%"
      @close="rightsDialogClosed"
    >
      <!-- 分配权限的树形控件 -->
      <el-tree
        :data="rightsTree"
        show-checkbox
        node-key="id"
        ref="tree"
        default-expand-all
        :default-checked-keys="selectedDefKeys"
        :props="defaultProps"
      >
      </el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 控制分配权限对话框的显示隐藏
      rightsDialogVisible: false,
      // 树状权限数据
      rightsTree: [],
      // 树形控件配置选项
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      // 选中叶子节点数组
      selectedDefKeys:[],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
    },
    // 删除角色指定权限
    async removeRight(role, rightId) {
      // console.log(role);
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('取消权限失败！')
      }
      // 重新获取角色列表会导致展开行关闭，用户体验不好
      // this.getRolesList()
      // 由于返回数据中的data是当前角色下最新的权限数据，所以直接把整个角色对象scope.row
      // 传递过来，直接赋值给children，避免整个表格数据重新渲染导致展开行关闭，用户体验不好
      role.children = res.data
    },
    // 获取树状权限数据
    async getRightsTree() {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败！')
      }
      this.rightsTree = res.data
    },
    // 通过递归的方式将选中的叶子节点的id遍历出来
    getLeafKeys(arr) {
      arr.forEach(item => {
        if (!item.children) {
          return this.selectedDefKeys.push(item.id)
        }
        this.getLeafKeys(item.children)
      })
    },
    // 显示分配权限的对话框
    showDialogVisible(role) {  
      this.roleId = role.id
      // 1.获取树状权限数据
      this.getRightsTree()
      // 2.获取当前角色选中的叶子节点的id放入数组中
      this.getLeafKeys(role.children)
      // 3.显示对话框
      this.rightsDialogVisible = true
    },
    // 分配权限对话框关闭事件
    rightsDialogClosed() {
      this.selectedDefKeys = []
    },
    // 点击确定，为角色分配权限
    async allotRights() {
      let CheckedKeysArr =  this.$refs.tree.getCheckedKeys()
      let HalfCheckedKeysArr =  this.$refs.tree.getHalfCheckedKeys()
      // console.log('全选中：');
      // console.log(CheckedKeysArr);
      // console.log('半选中：');
      // console.log(HalfCheckedKeysArr);
      let AllCheckedKeysArr = [...CheckedKeysArr,...HalfCheckedKeysArr]
      let idStr = AllCheckedKeysArr.join(',')
      // 发起请求，为角色分配权限
      console.log(this.roleId);
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`,{
        rids: idStr
      })
      if (res.meta.status !== 200) {
        this.rightsDialogVisible = false
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')

      // 重新获取角色列表
      this.getRolesList()
      // 隐藏对话框
      this.rightsDialogVisible = false
    }
  },
}
</script>

<style lang="less" scoped>
.row-padding {
  padding: 0 8px;
  /* 
  这样写不行，因为二级权限的个数是动态的
  &:nth-child(-n+2) {
    
    border-bottom: 1px solid #eee;
  } */
  .secondPart-left {
    margin-top: 8px;
  }
  .secondPart-right {
    margin: 8px;
  }
}
.vcenter {
  display: flex;
  align-items: center;
}
.bbottom {
  border-bottom: 1px solid #eee;
}
.btop {
  border-top: 1px solid #eee;
}
.mr {
  margin-right: 5px;
}
</style>
